import { createMemoryHistory, createRouter } from 'vue-router'
const p_modules = import.meta.glob("@/page/*/index.vue")
const c_modules = import.meta.glob("@/view/*/index.vue")

type myRouterType = {
    path: string
    name?: string
    redirect?: string
    children?: Array<myRouterType>
    component?: any
}
type routerItemType = {
    key: string
    redirect?: string
    children?: Array<string>
}
const router_list = [
    {
        key: "login",
        children: []
    },
    {
        key: "主页",
        children: []
    }
]
const router_meta_list = [
    {
        key: "login",
        meta: {
            title: "登录"
        }
    }
]
function init() {
    const routes: Array<myRouterType> = [
        {
            path: "/",
            redirect: "login"
        }
    ]
    for (let [key, val] of Object.entries(p_modules)) {
        const splits = key.split("/")
        const name = splits[splits.length - 2]
        const p_router = router_list.find(el => el.key == name)
        if (!p_router) continue
        const children = []
        for (let [c_key, c_val] of Object.entries(c_modules)) {
            const c_splits = c_key.split("/")
            const c_name = c_splits[c_splits.length - 2]
            const c_router = p_router.children.find(el => el == c_name)
            if (!c_router) continue
            children.push(generated_router(c_router, c_val))
        }
        routes.push(generated_router(p_router, val, children))
    }
    return routes
}
function generated_router(options: routerItemType, component: any, children?: Array<myRouterType>): myRouterType {
    return {
        path: `/${options.key}`,
        name: options.key,
        redirect: options.redirect,
        component,
        children: children || []
    }
}
const router = createRouter({
    history: createMemoryHistory(),
    routes: init() as any
})
export default router